<?php
$serverURL="http://crafts.hopmart.pl/files/illredirb";
$VERSION="0.94";
$DISCLAIMER=<<<DISCLAIMER
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
DISCLAIMER;

$INSTRUCTIONS=<<<INSTRUCTIONS
THIS SCRIPT WILL TRY TO REMOVE JS-ILLREDIR-B/C MALLICIOUS ENTRIES FROM ALL
.php, .htm, .html, and .js FILES IN CURRENT ('.') DIRECTORY AND ALL OF
ITS SUBDIRECTORIES. THIS WILL MODIFY YOUR FILES AND MAY BE IRREVERSIBLE!
PLEASE BACKUP YOUR FILES BEFORE RUNNING THIS SCRIPT. YOU HAVE TO HAVE
MODIFY FILE PERMISSON LEVEL FOR THIS FIX TO BE SUCCESSFULL. THIS SOFTWARE
IS DISTRIBUTED UNDER GNU GPL LICENSE (http://www.gnu.org/licenses/gpl.html) 
AND CAN BE MODIFIED TO SUIT YOUR NEEDS.<br/>
YOU ARE USING THIS SOFTWARE ON YOUR OWN RESPONSIBILITY!<br/><br/>

MORE INFORMATION IS AVALILABLE HERE: <a target="_new" href="http://www.zyenweb.com/2009/12/30/trojan-attack-jsillredir-b-trj/">ZynWeb</a>, <a target="_new" href="http://forum.php.pl/JavaScriptHTMLZabezpieczenia_t136469.html">PHP.pl</a><br/><br/>

USAGE:<br/>
HTTP: CLICK 'Start' button.<br/>
COMMANDLINE: php remove-js-illredir-b.php --run

INSTRUCTIONS;
$isManual = !isset($_SERVER['REMOTE_ADDR']);
$shouldRun = $argv[1] == "--run" || $_GET['action'] == 'run';
$dir = ".";

if ($shouldRun) {
	if (version_compare(PHP_VERSION, '5.0', "lt")) {
		die("You need at least php version 5.0<br/>\n");
	}
	if ($isManual) {
		echo $DISCLAIMER;
	}
	echo "\nPHP version: ".PHP_VERSION."<br/>\n";
	echo "Starting ...<br/>\n";
	$cleaner = new JSIllRedirBCleaner();
	fixDir($cleaner, $dir);
	$cleaner->displayStats();
} else if ($isManual) {
	echo $DISCLAIMER."\n\n";
	echo $INSTRUCTIONS;
}

function fixDir($cleaner, $dir) {
	$dh = opendir($dir);
	if ($dh === false) {
		echo "Cannot open directory $dir<br/>\n";
		return;
	}
	while (($file = readdir($dh)) !== false) {
		$fileName = $dir."/".$file;
//		echo "Trying $fileName<br/>\n";
		$fileType = filetype($fileName);
		if ($fileType == 'dir') {
			if ($file != "." && $file != "..") {
//				echo "Entering $fileName<br/>\n";
				fixDir($cleaner, $fileName);
			}
		} else if ($fileType == 'file') {
//			echo "File: $file<br/>\n";
			if (substr($file,-4) == ".htm" || substr($file,-5) == ".html" || substr($file,-3) == ".js" || substr($file,-4) == ".php") {
//				echo "Cleaning: $file<br/>\n";
				$cleaner->clean($fileName);
				flush();
			}
		}
	}
//	echo "$dir done.<br/>\n";
}

class JSIllRedirBCleaner {
	private $file;
	private $contents;
	private $numProcessed = 0;
	private $numFixed = 0;
	
	function clean($file) {
		$this->file = $file;
		$this->contents = null;
		$this->count = 0;
		$this->numProcessed++;
		if ($this->read()) {
			if (strlen($this->contents) > 0) {
				if ($this->detect()) {
					$this->cleanContents();
					$this->write();
				}
			}
		}
	}
	
	function read() {
		$size = filesize($this->file);
		if ($size) {
			$fd = fopen($this->file, "r");
//			echo "File opened: $this->file<br/>\n";
			if ($fd !== false) {
				$this->contents = fread($fd, $size);
//				echo "File read: $this->file<br/>\n";
				fclose($fd);
				return true;
			}
		}
		return false;
	}
	
	function detect() {
//		echo "Detecting $this->file ...<br/>\n";
		$pattern = '/\/\*(GNU |L)GPL\*\/ try\{( )?window\.onload = function\(\)\{var ([a-zA-Z0-9_]+) = document\.createElement\(/';
		if (preg_match($pattern, $this->contents, $match)) {
//			echo "$this->file ... matches !<br/>\n";
			$this->varName =  $match[3];
//			echo "Detected $pattern<br/>\n";
//			echo "Used varName: $this->varName<br/>\n"; 
			return true;
		}
//		echo "$this->file ... does not match !<br/>\n";
		$this->varName = null;
		return false;
	}
	
	function cleanContents() {
		$pattern = '\/\*(GNU |L)GPL\*\/ try\{( )?window\.onload = function\(\)\{var '.$this->varName.'.*\.appendChild\('.$this->varName.'\)\;\}\}( \})? catch\([a-z0-9A-Z_]+\) \{\}';
		if (substr($this->file,-3) != ".js") {
			$pattern = "\<script\>$pattern\<\/script\>";
		}
//		echo "Trying pattern: /$pattern/<br/>\n";
		$this->contents = preg_replace("/".$pattern."/", "", $this->contents, -1, $this->count);
//		echo "Fixed contents:<br/>\n $this->contents"; 
	}
	
	function  write() {
		if ($this->count > 0) {
			$fd = fopen($this->file, "w");
			if ($fd !== false) {
				$written = fwrite($fd, $this->contents);
				if ($written != 0 && $written !== false) {
					echo "$this->file ... fixed!<br/>\n";
					$this->numFixed++;
				} else {
					echo "$this->file cannot write !<br/>\n";
				}
				fclose($fd);
			} else {
				echo "$this->file cannot be modified !<br/>\n";
			}
		} else {
			echo "$this->file could not fix !<br/>\n";
		}
	}
	
	function displayStats() {
		echo "<br/>\nFiles processed: $this->numProcessed<br/>\n";
		echo "Files fixed: $this->numFixed\n\n";
	}
}
function cleanupStringForJs($str) {
	return str_ireplace(array("\n", "'"), array(" ", "\\'"), $str);
}
if ($isManual || $shouldRun) {
	die("");
}
$START_TAB = <<<START_TAB
<div id="msg1"><b>WHAT DOES THIS SCRIPT DO</b><br/>
$INSTRUCTIONS
</div>
<div id="msg2"><b>DISCLAIMER</b><br />
$DISCLAIMER
</div>
<div id="msg3">IF YOU AGREE WITH ABOVE PRESS START BUTTON</div>
<div id="start"><a href="?action=run" onclick="runMe(); return false;"><img src="$serverURL/img/start.jpg"
	alt="Start" title="Start" width="185" height="86" border="0"></a></div>
START_TAB;

$INSTRUCTIONS_TAB =<<<INSTRUCTIONS_TAB
<div id="msg1"><b>IMPORTANT</b><br />
<ol>
    <li>If your anti-virus software does not detect Trojan IllRedir-B/C use Avast instead.</li>
    <li>Don't use Total Commander as an FTP client use Filezilla instead.</li>
    <li>Remove all the passwords from your Total Commander installation.</li>
    <li>Change all the passwords stored previously in Total Commander (change them on the server).</li>
    <li>Use this tool on the server to fix all infected files.</li>
</ol>
<b>INSTALLATION AND USAGE</b><br/>
<ol>
    <li>Place this script in the <b>root or public_html</b> web directory on the infected server.</li>
    <li>This script will modify contents of all infected files, please backup all files before executing this script.</li>
	<li>For manual or crontab use run command: 'php remove-js-illredir-b.php --run' to execute.</li>
	<li>If you don't have shell access or prefer <b>graphical interface</b> you have to access the script via HTTP.</li>
	<li>After script page has loaded, read important disclaimer and click 'Start' button.</li>
	<li>Script will navigate through all subdirectories and will try to fix all infected files.</li>
	<li>User running the script (or HTTP server) have to have navigation/execution ('x') rights to all <b>subdirectories</b> for this script to work properly.</li>
	<li>In case of invalid directory permissions 'lstat()' errors will show up.</li>
	<li>Also, user running the script (or HTTP server) will have to have write ('w') permissions to all infected files, so they may be re-saved.</li>
	<li>Script will notify you when it has no permissions to modify the file.</li>
	<li>Some basic statistics are being collected and reported at the end of the script's execution.</li>
</ol>
</div>
INSTRUCTIONS_TAB;

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<title>Ill Redir-B/C removal tool - version <?=$VERSION?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
	<link href="<?=$serverURL?>/style.css" rel="stylesheet" type="text/css"></link>
	<script src="<?=$serverURL?>/prototype.js" type="text/javascript"></script>
	<script type="text/javascript">
		function goToStart() {
			$('content').innerHTML = '<?=cleanupStringForJs($START_TAB)?>';
			styleTabs();
			Element.addClassName('tabStart', 'activ');
		}
		function goToInstructions() {
			$('content').innerHTML = '<?=cleanupStringForJs($INSTRUCTIONS_TAB)?>';
			styleTabs();
			Element.addClassName('tabInstructions', 'activ');
		}
		function styleTabs() {
			Element.removeClassName('tabStart', 'activ');
			Element.addClassName('tabStart', 'nactiv');
			
			Element.removeClassName('tabInstructions', 'activ');
			Element.addClassName('tabInstructions', 'nactiv');
			
			Element.removeClassName('tabContact', 'activ');
			Element.addClassName('tabContact', 'nactiv');
		}
		function runMe() {
			$('content').innerHTML = '<div id="scriptOutput">Running...</div>';
			new Ajax.Request('',
  				{
    				parameters:  { action: 'run', rnd: Math.random() },
    				onComplete: processResponse,
					onInteractive: processResponse,
    				method: 'get' 
  				}); 
		}
		function processResponse(transport) {
			var current = $('scriptOutput').innerHTML;
			Element.insert($('scriptOutput'), { bottom: "<span>" + transport.responseText.substring(current.length-10) + "</span>"});
	    }
	</script>
</head>
<body>
<div id="page">
<div id="mainpage">
<div id="heder">
<div id="linia">
<div id="logo"><a href="http://www.hopmart.pl"><img
	src="<?=$serverURL?>/img/logo.jpg" alt="Hopmart store" title="Hopmart store" width="49"
	height="45" border="0" /></a></div>
<h1>Ill Redir-B/C<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Removal Tool - version <?=$VERSION?></h1>
<div id="donate"><a
	href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=10886359"><img
	src="<?=$serverURL?>/img/donate.jpg" alt="Donate Us" title="Donate Us" width="183"
	height="84" border="0"/></a></div>
<div id="nav">
<ul class="menu">
	<li id="tabStart" class="activ"><a href="" onclick="goToStart(); return false;">Start</a></li>
	<li id="tabInstructions" class="nactiv"><a href="" onclick="goToInstructions(); return false;">Instructions</a></li>
	<li id="tabContact" class="nactiv"><a href="mailto:illredirb@hopmart.com">Contact</a></li>
</ul>
</div>
</div>
</div>
<div id="content">
<?=$START_TAB?>
</div>
<div id="footer">
<div id="copy">&copy; 2010 <a href="http://crafts.hopmart.pl">HopmArt.pl</a><span style="margin-left: 540px;">Authors: Michał Jung and Marcin Jung<br/>Version: <?=$VERSION?></span></div>
</div>
</div>
</div>
</body>
</html>
